package mess;

import java.util.Arrays;
import java.util.EmptyStackException;

public class LeeCode_43 {
    public static void main(String[] args) {
        System.out.println(multiply("140", "721"));
    }
    private static String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2))
            return "0";
        int len1 = num1.length();
        int len2 = num2.length();
        String[] sArr = new String[len2];
        int temp = 0;
        for (int i = len2 - 1; i >= 0; i--) {
            temp = 0;
            StringBuilder sb = new StringBuilder();
            char c2 = num2.charAt(i);
            int n2 = c2 - 48;
            for (int j = len1 - 1; j >= 0; j--) {
                char c1 = num1.charAt(j);
                int n1 = c1 - 48;
                int mul = n1 * n2;

                int n3 = (mul % 10 + temp) % 10;
                sb.append(n3);
                temp = (mul  + temp) / 10;
                if (j == 0 && temp > 0)
                    sb.append(temp);
            }
            sArr[len2 - i - 1] = sb.reverse().toString();
        }

        int arrLen = sArr.length;
        int count = sArr[arrLen - 1].length() + len2 - 1;
        StringBuilder sb = new StringBuilder();
        temp = 0;
        for (int i = 0; i < count; i++) {
            int[] arr = new int[arrLen];
            for (int j = 0; j < arrLen; j++) {
                if (j <= i){
                    int index = sArr[j].length() - 1 - i + j;
                    arr[j] = index >= 0 ? sArr[j].charAt(index) - 48 : 0;
                }else
                    arr[j] = 0;
            }
            int sum = 0;
            for (int k : arr)
                sum += k;
            int n = (sum + temp) % 10;
            temp = (sum + temp) / 10;
            sb.append(n);
            if (i == count - 1 &&  temp > 0)
                sb.append(temp);
        }
        return sb.reverse().toString();
    }
}
